<template>
  <page-card title="用户管理"
             :sub-title="subTitle"
             :need-back="true"
             ref="editPage">
    <slot name="form" />
    <a-row v-if="!$slots.form"
           type="flex"
           justify="center">
      <a-col :span="24">

        <a-form-model :model="form"
                      :rules="rules"
                      :label-col="{ span: 6 }"
                      :wrapper-col="{ span: 12 }"
                      ref="form">
          <a-col :span="6"></a-col>

          <a-col :span="24">
            <a-divider orientation="left">
              基本信息
            </a-divider>
          </a-col>
          <a-input type="hidden"
                   v-model="form.id" />
          <a-input type="hidden"
                   v-model="form.unitId" />
          <a-input type="hidden"
                   v-model="form.deptId" />
          <a-input type="hidden"
                   v-model="form.userVO.passwordSalt" />
          <a-form-model-item label="所属机构">
            {{form.deptVO.belongs}}
          </a-form-model-item>
          <a-form-model-item label="头像："
                             prop="userVO.img">
            <z-image-uploader :isQuery="imgUpload.isQuery"
                              :showUploadList="imgUpload.showUploadList"
                              :parentId="form.userVO.id"
                              :accept="'image/gif,image/png,image/jpeg'"
                              :bucketName="imgUpload.bucketName"
                              :systemName="imgUpload.systemName"
                              :limit="1"
                              :configGroup="imgUpload.configGroup"
                              v-model="form.userVO.fileList"
                              ref="imgUploader" />
          </a-form-model-item>
          <a-form-model-item label="姓名："
                             prop="userVO.fullname">
            <a-input placeholder="用户姓名，长度最少2位，不超过20位"
                     :maxLength="20"
                     v-model.trim="form.userVO.fullname"
                     allow-clear />
          </a-form-model-item>
          <a-form-model-item label="性别："
                             prop="userVO.sex">
            <a-radio-group name="radioGroup"
                           v-model="form.userVO.sex">
              <a-radio value="1">男</a-radio>
              <a-radio value="2">女</a-radio>
              <a-radio value="3">未知</a-radio>
            </a-radio-group>
          </a-form-model-item>

          <a-form-model-item label="账号："
                             prop="userVO.account">
            <a-input placeholder="用户账号，长度最少2位，不超过20位"
                     :maxLength="20"
                     @keydown="isCheckPassword = true"
                     v-model.trim="form.userVO.account"
                     allow-clear />
          </a-form-model-item>

          <a-form-model-item label="密码："
                             prop="userVO.password">
            <a-input ref="userpass"
                     type="password"
                     v-model.trim="form.userVO.password"
                     :maxLength="20"
                     :placeholder="placeHolder"
                     allow-clear>
              <a-icon slot="addonAfter"
                      type="eye"
                      v-if="!!this.form.id"
                      @click="seePass" />
            </a-input>
          </a-form-model-item>
          <!-- :disabled="true" -->
          <a-form-model-item label="角色："
                             prop="roleIdList">
            <a-select v-model="form.roleIdList"
                      mode="multiple"
                      :default-value="form.roleIdList"
                      style="width: 100%"
                      :filterOption="filterOption"
                      placeholder="该用户角色">
              <a-select-option v-for="(role) in roleListData"
                               :class="{'user-edit-role-disabled':role.status === '0'}"
                               :key="role.id"
                               :value="role.id">
                {{ role.name }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item label="排序号："
                             prop="orderno">
            <a-input-number placeholder="正整数排序号"
                            v-model.trim="form.orderno"
                            style="width:100%"
                            :min="1"
                            :max="1000000"
                            allow-clear />
          </a-form-model-item>
          <a-form-model-item label="状态："
                             prop="userStatusList">
            <a-select style="width: 100%"
                      allowClear
                      v-model="form.userVO.status"
                      placeholder="该用户状态">
              <a-select-option v-for="(userStatus) in userStatusList"
                               :disabled="userStatus.remark === 'disabled'"
                               :key="userStatus.id"
                               :value="userStatus.dictKey">{{ userStatus.dictValue }}</a-select-option>
            </a-select>
          </a-form-model-item>
          <!-- 如果状态设置为锁定就禁用并且设置时间为当前 -->
          <a-form-model-item label="过期时间："
                             prop="expiredDate">
            <a-date-picker allow-clear
                           :disabled="form.userVO.status == 4"
                           v-model="form.userVO.expiredDate"
                           show-time
                           @change="expiredDateChange"
                           format="YYYY-MM-DD HH:mm"
                           type="date"
                           placeholder="创建临时用户时，该用户登录的有效期限，创建正常用户不必填"
                           style="width: 100%;" />
          </a-form-model-item>
          <a-form-model-item label="主题："
                             prop="theme">
            <a-radio-group name="radioGroup"
                           v-model="form.userVO.theme">
              <a-radio v-for="(theme,index) in themeList"
                       :key="index.tostring"
                       :value="theme.dictKey">
                {{ theme.dictValue }}
              </a-radio>
            </a-radio-group>
          </a-form-model-item>
          <a-form-model-item label="手机号码："
                             prop="userVO.tel">
            <a-input placeholder="手机号码，长度不超过11位"
                     :maxLength="11"
                     v-model.trim="form.userVO.tel"
                     allow-clear />
          </a-form-model-item>
          <a-form-model-item label="联系地址："
                             prop="userVO.address">
            <a-input placeholder="联系地址，长度不超过100位"
                     :maxLength="100"
                     v-model.trim="form.userVO.address"
                     allow-clear />
          </a-form-model-item>

          <!-- <a-form-model-item label="过期时间："
                             prop="expiredDate">
            <a-date-picker allow-clear
                           v-model="form.userVO.expiredDate"
                           show-time
                           format="YYYY-MM-DD HH:mm"
                           type="date"
                           placeholder="创建临时用户时，该用户登录的有效期限，创建正常用户不必填"
                           style="width: 100%;" />
          </a-form-model-item> -->

          <a-form-model-item label="出生日期："
                             prop="userVO.birthday">
            <a-date-picker allow-clear
                           format="YYYY-MM-DD"
                           default-value=""
                           v-model="form.userVO.birthday"
                           placeholder="用户出生日期"
                           style="width: 100%;" />
          </a-form-model-item>

          <a-form-model-item label="邮箱："
                             prop="userVO.email">
            <a-input placeholder="用户邮箱，长度不超过100位"
                     :maxLength="100"
                     v-model.trim="form.userVO.email"
                     allow-clear />
          </a-form-model-item>

          <a-form-model-item label="身份证号："
                             prop="userVO.idCard">
            <a-input placeholder="用户身份证号，长度不超过18位"
                     :maxLength="18"
                     v-model.trim="form.userVO.idCard"
                     allow-clear />
          </a-form-model-item>

          <a-form-model-item label="钉钉ID："
                             help="接入钉钉用户时，对应其钉钉用户id"
                             prop="userVO.zwddId">
            <a-input placeholder="接入钉钉系统时，对应其钉钉用户ID，长度不超过100位"
                     v-model.trim="form.userVO.zwddId"
                     :maxLength="100"
                     allow-clear />
          </a-form-model-item>

          <a-form-model-item label="用户OPENID："
                             help="三方系统接入纵横时，对应纵横的用户id"
                             prop="userVO.openId">
            <a-input placeholder="用户开放平台ID"
                     v-model.trim="form.userVO.openId"
                     disabled />
          </a-form-model-item>

          <a-form-model-item label="第三方应用ID："
                             help="接入第三方用户中心系统时，对应其用户ID"
                             prop="userVO.otherSysId">
            <a-input placeholder="接入第三方用户中心系统时，对应其用户ID"
                     v-model.trim="form.userVO.otherSysId" />
          </a-form-model-item>
          <!-- 密级 -->
          <a-form-model-item label="mj："
                             v-if="authorize.includes('secretyLevel')">
            <a-select style="width: 100%"
                      allowClear
                      v-model="form.userVO.secretLevel"
                      placeholder="mj">
              <a-select-option v-for="secretyLevel in secretyLevelList"
                               :key="secretyLevel.id"
                               :value="secretyLevel.id">{{ secretyLevel.name }}</a-select-option>
            </a-select>
          </a-form-model-item>

          <a-form-model-item label="备注："
                             style="height: 94px;">
            <a-textarea placeholder="对用户信息备注说明，长度不超过200位"
                        :maxLength="200"
                        :rows="4"
                        v-model.trim="form.userVO.remark"
                        allow-clear />
          </a-form-model-item>
          <a-col :span="24">
            <a-divider orientation="left">
              岗位信息
            </a-divider>
          </a-col>

          <a-form-model-item label="主职标识："
                             prop="isMainJob">
            <a-radio-group name="radioGroup"
                           v-model="form.isMainJob">
              <a-radio value="1">主职</a-radio>
              <a-radio value="2">兼职</a-radio>
            </a-radio-group>
          </a-form-model-item>

          <a-form-model-item label="职级名称："
                             prop="occName">
            <a-select allowClear
                      placeholder="请选择职级"
                      v-model="form.occLevel"
                      @change="levelChange">
              <a-select-option v-for="(item,index) in levelList"
                               :value="item.occLevel"
                               :key="index">
                {{ item.occName }}
              </a-select-option>
            </a-select>
          </a-form-model-item>

          <a-form-model-item label="岗位名称："
                             prop="jobName">
            <a-select allowClear
                      placeholder="请选择岗位"
                      v-model="form.jobCode"
                      @change="jobChange">
              <a-select-option v-for="(item,index) in jobList"
                               :value="item.jobCode"
                               :key="index">
                {{ item.jobName }}
              </a-select-option>
            </a-select>
          </a-form-model-item>

          <!-- <a-form-model-item label="岗位名称："
                             prop="jobName">
            <a-input placeholder="用户在该机构下的岗位名称，长度不超过50位"
                     :maxLength="50"
                     v-model="form.jobName"
                     allow-clear />
          </a-form-model-item> -->
          <a-form-model-item label="入职日期："
                             prop="joinTime">
            <a-date-picker v-model="form.joinTime"
                           :defaultValue="moment('2015-01-01', 'YYYY-MM-DD')"
                           type="date"
                           placeholder="用户入职日期"
                           style="width: 100%;" />
          </a-form-model-item>
          <a-form-model-item label="工号："
                             prop="workNo">
            <a-input placeholder="用户在该机构下的工号，长度不超过20位"
                     :maxLength="20"
                     v-model.trim="form.workNo"
                     allow-clear />
          </a-form-model-item>
          <a-form-model-item label="联系电话："
                             prop="tel">
            <a-input placeholder="联系电话，长度不超过20位"
                     :maxLength="20"
                     v-model="form.tel"
                     allow-clear />
          </a-form-model-item>

          <a-form-model-item label="公司邮箱："
                             prop="email">
            <a-input placeholder="公司邮箱，长度不超过100位"
                     v-model.trim="form.email"
                     :maxLength="100"
                     allow-clear />
          </a-form-model-item>

          <a-form-model-item label="状态："
                             prop="state">
            <a-radio-group name="radioGroup"
                           v-model="form.state">
              <a-radio value="1">在职</a-radio>
              <a-radio value="2">离职</a-radio>
            </a-radio-group>
          </a-form-model-item>
          <a-col v-if="extendData.length>0"
                 :span="24">
            <a-divider orientation="left">
              扩展信息
            </a-divider>
          </a-col>
          <a-form-model-item v-for="item in extendData"
                             :key="item.id"
                             :label="item.columnsName"
                             :prop="item.columnsValue">

            <!-- 文本框 -->
            <a-input allowClear
                     :disabled="item.isUpdate == 0"
                     v-if="item.columnsType == 1"
                     :placeholder="'请输入'+item.columnsName"
                     v-model.trim="form[item.columnsValue]" />
            <!-- 下拉框 -->
            <a-select allowClear
                      :disabled="item.isUpdate == 0"
                      v-if="item.columnsType == 2"
                      :placeholder="'请选择'+item.columnsName"
                      v-model="form[item.columnsValue]">
              <a-select-option v-for="(itemSelect,index) in item.source"
                               :value="itemSelect.value"
                               :key="index">
                {{ itemSelect.label }}
              </a-select-option>
            </a-select>
            <!-- 单选框 -->
            <a-radio-group v-if="item.columnsType == 3"
                           :disabled="item.isUpdate == 0"
                           :options="item.source"
                           v-model="form[item.columnsValue]"
                           :default-value="radioDefault(item.source)" />
            <!-- 时间组件 -->
            <a-date-picker v-if="item.columnsType == 4"
                           :disabled="item.isUpdate == 0"
                           v-model="form[item.columnsValue]"
                           style="width:100%"
                           show-time
                           :format="item.source.format" />
          </a-form-model-item>
        </a-form-model>
      </a-col>
    </a-row>
    <div style="text-align:center; padding:30px">
      <a-space size="small">
        <slot name="buttons" />
        <template v-if="!$slots.buttons">
          <a-button v-if="!!this.form.id"
                    style="width: 80px;"
                    @click="del">删除</a-button>
          <a-button type="primary"
                    style="width: 80px;"
                    @click="save">保存</a-button>
        </template>
      </a-space>
    </div>
  </page-card>
</template>

<script>
import moment from 'moment'
import { showPassFun, init, getById, getAllRoleList, del, saveOrUpdate, recordBasic, getRoleListByJobBankId } from '../../api/user/index'
import { getNoCacheCodeListByCode } from '../../api/dictionary/index'
import { getSysSystemSettingInfo } from '../../api/setting/index'
import { getRankList as pageLevel } from '../../api/job/rank'
import { getJobList as pageJob } from '../../api/job/index'
import { getSyProperties, getPersonList } from "../../api/mj";
export default {
  props: {
    onSave: {
      type: Function,
      default: null
    },
    onDelete: {
      type: Function,
      default: null
    }
  },
  data () {
    return {
      levelList: [],
      jobList: [],
      extendData: [],
      flag: true,
      syncOff: false,
      syncVisible: false,
      themeList: [],
      mediaType: '2',
      syncType: '',
      deptId: '',
      mediaId: '',
      moment,
      showPass: true,
      subTitle: '',
      roleListData: [],
      roleIdList: [],
      userStatusList: [],
      secretyLevelList: [],
      activeKey: ['1'],
      placeHolder: '',
      isCheckPassword: false,
      imgUpload: {
        parentId: '',
        fileList: [], // 图片列表集合
        isQuery: false, // 当此参数为true时表示其功能不可上传图片
        showUploadList: true, // 是否显示图片列表
        bucketName: 'zongheng-system', // 当前归属系统所在的空间名称
        systemName: 'ykz-system', // 归属系统名称
        configGroup: 'user_img'
      },

      form: {
        id: null,
        joinTime: null,
        occLevel: null,
        occName: '',
        jobCode: '',
        jobName: '',
        userVO: {
          fileDto: null,
          id: null,
          type: '',
          fullname: '',
          img: null,
          account: '',
          password: '',
          tempPassWord: null,
          tel: '',
          status: '1',
          sex: '',
          birthday: null,
          email: '',
          address: '',
          remark: '',
          zwddId: '',
          otherSysId: '',
          openId: '',
          idCard: '',
          unitIds: '',
          passwordSalt: '',
          secretLevel: undefined,
          expiredDate: null
        },
        unitVO: {
          id: null,
          name: '',
          fullName: '',
          parentId: 0,
          actual: '1',
          code: '',
          orderNo: '',
          levelCode: '',
          state: '1',
          type: '1',
          openId: '1',
          otherSysId: '1',
          url: '',
          zwddId: '',
          contact: '',
          unitAddress: '',
          tel: '',
          unitnote: ''
        },
        deptVO: {
          id: null,
          name: '',
          fullName: '',
          parentId: 0,
          actual: '1',
          code: '',
          orderNo: '',
          levelCode: '',
          state: '1',
          type: '1',
          openId: '1',
          otherSysId: '1',
          url: '',
          zwddId: '',
          contact: '',
          unitAddress: '',
          tel: '',
          unitnote: '',
          config: {}
        }
      },
      rules: {
        'userVO.fullname': [
          { required: true, message: '请输入用户姓名' },
          { min: 2, max: 20, message: '长度最少2位，不超过20位' }
        ],
        'userVO.account': [
          { required: true, message: '请输入用户账号' },
          { min: 2, max: 20, message: '长度最少2位，不超过20位' }
        ],
        'userVO.sex': [
          { required: true, message: '请输入用户性别' }
        ],
        'userVO.password': [
          { required: true, message: '请输入用户密码' }
        ],
        'userVO.tel': [
          { pattern: /^1\d{10}$/, message: '手机格式不正确' }
        ],
        'userVO.email': [
          { type: 'email', message: '邮箱格式不正确' }
        ],
        'userVO.idCard': [
          { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '身份证格式不正确' }
        ],
        email: [{ type: 'email', message: '邮箱格式不正确' }],
        tel: [
          { pattern: /^1\d{10}$/, message: '联系电话格式不正确' }
        ],
        orderno: [
          { required: true, message: '请输入排序号' },
          { pattern: /^[1-9]\d*$/, message: '排序号应该为正整数' }
        ],
        isMainJob: [{ required: true, message: '请选择用户主职标识' }],
        // roleIdList: [{ required: true, message: '请选择用户角色' }],
        userStatusList: [{ required: false, message: '请选择用户状态' }]
      }
    }
  },
  computed: {
    // 功能权限组
    authorize () {
      return this.$route.meta?._parent?.meta?.authorize || []
    }
  },
  beforeCreate () {
    this.syncOff = !this.$store.getAppConfig('_syncOff') || this.$store.getAppConfig('_syncOff') == 1
  },
  created () {
    !this.$slots.form && this.loadRole()
  },
  mounted () {
    if (!this.$slots.form) {
      this.loadDic()
      this.load()
      this.loadTheme()
      this.getSystemSettingInfo()
      this.getLevelList()
      this.getJobList()
      this.getPersonSecretyLevelList()
    }
  },
  methods: {
    // 获取 人员mj列表
    async getPersonSecretyLevelList () {
      const property = await getSyProperties()
      const list = property.enabled ? await getPersonList() : null
      this.secretyLevelList = list?.list || []
    },
    // 职级列表
    getLevelList () {
      let params = { occName: '' }
      pageLevel(params).then(res => {
        this.levelList = res || []
      })
    },
    // 岗位列表
    getJobList () {
      let params = { jobName: '' }
      pageJob(params).then(res => {
        this.jobList = res || []
      })
    },
    // 选择职级
    levelChange (value) {
      let item = this.levelList.find(e => {
        return e.occLevel == value
      })
      this.form.occName = item.occName
    },
    // 选择岗位
    jobChange (value) {
      let item = this.jobList.find(e => {
        return e.jobCode == value
      })
      this.form.jobName = item.jobName
      //通过岗位查询角色
      getRoleListByJobBankId(item.id).then(res => {
        if (res && res.length) {
          res.forEach(item => {
            this.form.roleIdList.push(item.id)
          })
        }
      })
    },
    // 将输入的内容与显示的内容进行匹配
    filterOption (value, option) {
      return option.componentOptions.children[0].text.indexOf(value) >= 0
    },
    // 系统设置
    getSystemSettingInfo () {
      getSysSystemSettingInfo().then((response) => {
        this.config = response
        // 包含数字、字母、特殊字符中至少两种，长度最少8位，不超过50位
        if (response.passTactics == '1') {
          if (response.passRule == '1') {
            this.placeHolder = '包含数字、字母，'
          } else if (response.passRule == '2') {
            this.placeHolder = '包含数字、字母、字符，'
          }
          this.placeHolder = this.placeHolder + '长度最少' + response.passMinLength + '位'
        } else {
          this.placeHolder = '请输入密码'
        }
      })
    },
    checkPlaceHolder () {
      return this.placeHolder
    },
    checkPattern (v) {
      if (this.config.passRule == 1) {
        let regu1 = /^(?=.*\d)(?=.*[a-zA-Z])(?=.*[~!@#$%^&*])[\da-zA-Z~!@#$%^&*]*$/
        let regu2 = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]+$/
        let re1 = new RegExp(regu1)
        let re2 = new RegExp(regu2)
        if (re1.test(v) || re2.test(v)) {
          return { code: true }
        } else {
          return { code: false, msg: '密码必须包含字母+数字' }
        }
      } else if (this.config.passRule == 2) {
        let regu1 = /^(?=.*\d)(?=.*[a-zA-Z])(?=.*[~!@#$%^&*])[\da-zA-Z~!@#$%^&*]*$/
        let re1 = new RegExp(regu1)
        if (re1.test(v)) {
          return { code: true }
        } else {
          return { code: false, msg: '密码必须包含字母+数字+符号' }
        }
      } else {
        return { code: true }
      }
    },
    /**
     * 单选框默认值判断
     */
    radioDefault (list) {
      for (let i in list) {
        if (list[i].default) {
          return list[i].value
        }
      }
    },
    /**
     * 加载主题类型
     */
    loadTheme () {
      getNoCacheCodeListByCode({ code: 'THEME' }).then(res => {
        this.themeList = res
      })
    },
    loadDic () {
      recordBasic().then((response) => {
        this.userStatusList = response
      })
    },
    /**
     * 加载当前用户角色
     */
    loadRole () {
      this.roleIdList = []
      getAllRoleList().then(res => {
        this.roleListData = res
      })
    },
    /**
     * 查看密码
     */
    seePass () {
      showPassFun(this.form.userVO.tempPassWord, this.form.userVO.passwordSalt).then(res => {
        this.message.info('密码为：' + decodeURIComponent(res))
      })
    },
    /**
     * 根据id参数 判断新增还是修改
     */
    load () {
      const id = this.$route.query.id
      const orgid = this.$route.query.orgid
      if (!id || id === '0') {
        this.subTitle = '新增'
        init(orgid).then(res => {
          this.form = res
          this.extendData = res.sysUserExtendData
          this.form.roleIdList = []
          this.extendData.forEach((item) => {
            if (item.columnsType == 2) {
              if (this.form[item.columnsValue] == null) {
                this.form[item.columnsValue] = []
              }
            }
            if (item.columnsType == 1 && item.isNull == 1) {
              this.rules[item.columnsValue] = [{
                required: true,
                message: '请输入' + item.columnsName
              }]
            }
            if (item.columnsType == 2 || item.columnsType == 3 || item.columnsType == 4) {
              if (item.source) {
                item.source = JSON.parse(item.source)
              }
              if (item.isNull == 1) {
                this.rules[item.columnsValue] = [{
                  required: true,
                  message: '请选择' + item.columnsName
                }]
              }
            }
            if (item.columnsType == 3) {
              for (let i in item.source) {
                if (item.source[i].default) {
                  this.form[item.columnsValue] = item.source[i].value
                }
              }
            }
          })
        })
      } else {
        this.subTitle = '编辑'
        getById(id).then(res => {
          this.form = res
          this.extendData = res.sysUserExtendData
          this.extendData.forEach((item) => {
            if (item.columnsType == 2) {
              if (this.form[item.columnsValue] == null) {
                this.form[item.columnsValue] = []
              }
            }
            if (item.columnsType == 3 && !this.form[item.columnsValue]) {
              if (item.source) {
                let list = JSON.parse(item.source)
                for (let i in list) {
                  if (list[i].default) {
                    this.form[item.columnsValue] = list[i].value
                  }
                }
              }
            }

            if (item.columnsType == 1 && item.isNull == 1) {
              this.rules[item.columnsValue] = [{
                required: true,
                message: '请输入' + item.columnsName
              }]
            }
            if (item.columnsType == 2 || item.columnsType == 3 || item.columnsType == 4) {
              if (item.source) {
                item.source = JSON.parse(item.source)
              }
              if (item.isNull == 1) {
                this.rules[item.columnsValue] = [{
                  required: true,
                  message: '请选择' + item.columnsName
                }]
              }
            }
          })
        })
      }
    },
    validImgFormer (fileName) {
      let reg = /\.(png|jpg|jpeg|gif)$/
      return reg.test(fileName)
    },
    // 过滤掉中文字符
    filterChineseChar (str = '') {
      return str.replace(/[\u4e00-\u9fa5]/g, '')
    },

    /**
     * 保存
     */
    save () {
      this.form.userVO.password = this.filterChineseChar(this.form.userVO.password)
      this.form.userVO.account = this.filterChineseChar(this.form.userVO.account)
      // 编辑时更改了密码才去校验
      if (this.config.passTactics == 1 && this.isCheckPassword) {
        let pw = this.form.userVO.password

        if (this.config.passMinLength > pw.length) {
          this.message.error('密码长度最少' + this.config.passMinLength + '位！')
          return
        }
        let re = this.checkPattern(pw)
        if (!re.code) {
          this.message.error(re.msg)
          return
        }
      }

      this.$refs.form.validate((valid) => {
        if (valid) {
          /**
           * 处理扩展字段
           */
          for (let i in this.form.sysUserExtendData) {
            let sourceList = this.form.sysUserExtendData[i].source
            for (let key in this.form) {
              if (this.form.sysUserExtendData[i].columnsValue == key) {
                for (let j in sourceList) {
                  if (this.form[key] == sourceList[j].value) {
                    this.form.sysUserExtendData[i].extendKey = sourceList[j].label
                  }
                }
                this.form.sysUserExtendData[i].extendValue = this.form[key]
                break
              }
            }
          }
          // 添加roleid
          const userForm = this.form
          userForm.roleIdList.concat(this.roleIdList)
          if (this.onSave) {
            // 调用自定义保存方法
            this.onSave(userForm).then((response) => {
              this.syncOff && this.sync(response.userId, this.form.id ? '2' : '1')
              !this.syncOff && this.$router.back()
            })
          } else {
            // 调用默认保存方法
            saveOrUpdate(userForm).then((response) => {
              this.syncOff && this.sync(response.userId, this.form.id ? '2' : '1')
              !this.syncOff && this.$router.back()
            })
          }
        }
      })
    },
    cancel () {
      this.syncVisible = false
      this.$router.back()
    },
    sync (id, syncType) {
      this.syncVisible = true
      this.mediaId = id
      this.deptId = this.$route.params.orgid
      this.syncType = syncType
    },
    /**
     * 删除
     */
    del () {
      const me = this
      this.confirm({
        content: '确定删除用户吗？',
        okText: '确认',
        cancelText: '取消',
        onOk () {
          if (me.onDelete) {
            // 调用自定义删除方法
            me.onDelete(me.form.id).then(res => {
              me.syncOff && me.sync(me.form.userId, '3')
              !me.syncOff && me.$router.back()
            })
          } else {
            // 调用默认删除方法
            del(me.form.id).then(res => {
              me.syncOff && me.sync(me.form.userId, '3')
              !me.syncOff && me.$router.back()
            })
          }
        }
      })
    },
    roleSelect (value, node) {
      /* 如果当前选中的是禁用的 就不选它 */
      if (node.data.class['user-edit-role-disabled']) {
        // 移除
        this.form.roleIdList = this.form.roleIdList.filter(item => item !== value)
      }
    },
    /* 设置过期时间为当前 */
    setExpiredDate () {
      const date = new Date()
      const expiredDate = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
      this.$set(this.form.userVO, 'expiredDate', expiredDate)
    },
    /* 设置状态为锁定 */
    expiredDateChange ({ _d: date }) {
      if (date <= new Date()) {
        this.$set(this.form.userVO, 'status', '4')
      }
    }
  },
  watch: {
    'form.userVO.fileList': {
      handler: function (newV, oldV) {
        if (oldV != newV && !!newV[0] && newV[0].name) {
          let fileName = newV[0].name
          if (!this.validImgFormer(fileName)) {
            this.flag = true
            if (this.flag && !!newV[0] && this.form.userVO.fileList.length > 0) {
              this.message.error('上传图片格式错误！')
              this.$refs.imgUploader.handleFileRemove(newV[0])
              this.form.userVO.fileList.splice(0, 1)
              this.flag = false
            }
            return
          }
        }
      }
    }
  }
}
</script>

<style lang="less" scoped>
.ant-input-affix-wrapper-textarea-with-clear-btn {
  height: 94px;
}
</style>
<style>
.user-edit-role-disabled {
  color: #aaa !important;
}
.user-edit-role-disabled:hover {
  cursor: no-drop;
}
</style>
